package com.ys.service.finance.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.EditDto;
import com.ys.entity.business.TpAmazonShopExchangeRate;
import com.ys.entity.finance.TcwDepositPlatform;
import com.ys.entity.finance.TcwDepositPlatformAccount;
import com.ys.entity.finance.TcwWanliPrepaymentPooling;
import com.ys.entity.purchase.TcgPurchaseOrderPay;
import com.ys.entity.storage.TccOnlinePurchaseReturn;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.enume.finance.TcwExchangeRateEnum;
import com.ys.enume.wanli.TransactionTypeListEnum;
import com.ys.enume.wanli.WfSubUserEnum;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.mapper.finance.TcwWanliPrepaymentPoolingMapper;
import com.ys.mapper.purchase.TcgPurchaseOrderPayMapper;
import com.ys.service.finance.TcwWanliPrepaymentPoolingService;
import com.ys.util.dhecp.DateUtils;
import com.ys.util.wanli.WanliUtils;
import com.ys.vo.ApiResponse;
import com.ys.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service("tcwWanliPrepaymentPoolingService")
public class TcwWanliPrepaymentPoolingServiceImpl implements TcwWanliPrepaymentPoolingService {

    @Autowired
    private DiySqlMapper diySqlMapper;

    @Autowired
    private TcwWanliPrepaymentPoolingMapper tcwWanliPrepaymentPoolingMapper;

    @Autowired
    private TcgPurchaseOrderPayMapper tcgPurchaseOrderPayMapper;


    /**
     * 万里汇流水明细。
     * @return
     */
    @Override
    public ApiResponse inquiryStatementList(TcwDepositPlatform tcwDepositPlatform) {
        ApiResponse apiResponse = new ApiResponse();
        JSONArray statementList;
        JSONObject statement;
        TcwWanliPrepaymentPooling tcwWanliPrepaymentPooling;
        JSONObject originalTransactionAmount;
        BigDecimal transferFromAmountValue;
        String jyCurrencyCode = null;
        JSONObject fundMoveDetail;
        List<TcwWanliPrepaymentPooling> tcwWanliPrepaymentPoolingList = new ArrayList<>();
        try {
            apiResponse.setCode(0);
            apiResponse.setMessage("获取成功!");
            String content = "";
            int pageNumber = 1;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("pageSize",50);

            //查询万里汇莫程账号clientId
            TbStaticConfig tbStaticConfigClientId = new TbStaticConfig()
                    .setKeyOne("wanli-mid")
                    .setKeyTwo("wanli-mid-clientId")
                    .queryFirst();


            //			上个月第一天
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -1);

            calendar.set(Calendar.HOUR_OF_DAY,00);
            calendar.set(Calendar.MINUTE,00);
            calendar.set(Calendar.SECOND,00);

            Date startTime = calendar.getTime();
            String startTimeStr = DateUtils.convertDateToTDate(startTime);

            calendar.set(Calendar.HOUR_OF_DAY,23);
            calendar.set(Calendar.MINUTE,59);
            calendar.set(Calendar.SECOND,59);

            Date endTime = calendar.getTime();
            String endTimeStr = DateUtils.convertDateToTDate(endTime);
            //TODO 前一天时间 未做
            jsonObject.put("startTime",startTimeStr);
            jsonObject.put("endTime",endTimeStr);
            //对过账的不允许操作该按钮
            if (new TcwWanliPrepaymentPooling().setReconciliationStatus(1).where("A.TransactionTime >= '"+ startTimeStr + "' AND A.TransactionTime <= '" + endTimeStr + "'").count() > 0){
                apiResponse.setCode(500);
                apiResponse.setMessage("昨天预付款归集明细已对账,不允许新数据导入!");
                return apiResponse;
            }
            //批量删除昨天数据
            diySqlMapper.deleteTcwWanliPrepaymentPoolingDate(startTimeStr,endTimeStr);

            List<String> transactionTypeList = new ArrayList<>();
            transactionTypeList.add(TransactionTypeListEnum.Type.FUND_COLLECTION.value);//归集
            jsonObject.put("transactionTypeList",transactionTypeList);
            String httpMethod = WfSubUserEnum.Type.POST.value;
            //主账号有子账号
            String clientId = tbStaticConfigClientId.getName();
            String uriWithQueryString = WfSubUserEnum.Type.INQUIRYBENEFICIARYLIST.value;
//            String connectedCustomerId = tcwDepositPlatform.getMid();
            String connectedCustomerId = "";

            boolean falx = true;
            while (falx){
                jsonObject.put("pageNumber",pageNumber);
                content = JSONObject.toJSONString(jsonObject);
                String result = WanliUtils.result(content, httpMethod, uriWithQueryString, clientId,connectedCustomerId);
                JSONObject resultJO = JSON.parseObject(result);
                JSONObject resultState = JSON.parseObject(resultJO.get("result").toString());
                //判断是否成功
                if (!resultState.get("resultStatus").toString().equals(WfSubUserEnum.Type.S.value)){
                    apiResponse.setCode(500);
                    apiResponse.setMessage(resultState.get("resultMessage").toString());
                    return apiResponse;
                }

                if (resultJO.get("statementList") != null){
                    statementList = JSON.parseArray(resultJO.get("statementList").toString());
                    for (int i = 0; i < statementList.size(); i++) {
                        statement = JSON.parseObject(statementList.get(i).toString());
                        //查询是否需要新增
                        if (new TcwWanliPrepaymentPooling().setTransactionId(statement.get("transactionId").toString()).count() == 0) {
                            tcwWanliPrepaymentPooling = new TcwWanliPrepaymentPooling();
                            tcwWanliPrepaymentPooling.setTransactionId(statement.get("transactionId").toString());
                            tcwWanliPrepaymentPooling.setTransactionType(statement.get("transactionType").toString());
                            //获取交易金额
                            originalTransactionAmount = JSON.parseObject(statement.get("originalTransactionAmount").toString());
                            if (originalTransactionAmount != null){
                                //JPY 不需要缩小100倍，其他都需要
                                jyCurrencyCode = originalTransactionAmount.get("currency").toString();
                                if (jyCurrencyCode.equals(TcwExchangeRateEnum.ExchangeRate.JPY.value)){
                                    transferFromAmountValue = new BigDecimal(originalTransactionAmount.get("value").toString());
                                }else {
                                    transferFromAmountValue = new BigDecimal(originalTransactionAmount.get("value").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入);
                                }
                                tcwWanliPrepaymentPooling.setOriginalTransactionAmount(transferFromAmountValue);
                                tcwWanliPrepaymentPooling.setJyCurrencyCode(jyCurrencyCode);
                            }
                            if (statement.get("extTransactionId") != null){
                                tcwWanliPrepaymentPooling.setExtTransactionId(statement.get("extTransactionId").toString());
                            }
                            tcwWanliPrepaymentPooling.setTransactionTime(statement.get("transactionTime").toString());
                            tcwWanliPrepaymentPooling.setTransactionStatus(statement.get("transactionStatus").toString());
                            //描述
                            fundMoveDetail = JSON.parseObject(statement.get("fundMoveDetail").toString());
                            if (fundMoveDetail != null){
                                tcwWanliPrepaymentPooling.setDescription(fundMoveDetail.get("description") == null?"空":fundMoveDetail.get("description").toString());
                                //付款人账号
                                if (fundMoveDetail.get("payerAccountNo") != null){
                                    tcwWanliPrepaymentPooling.setFkMid(fundMoveDetail.get("payerAccountNo").toString());
                                    tcwWanliPrepaymentPooling.setPayerName(fundMoveDetail.get("payerName").toString());
                                    tcwWanliPrepaymentPooling.setFkVyhsx(1);
                                    //根据付款人账号获取Mid
                                    TcwDepositPlatformAccount tcwDepositPlatformAccount = new TcwDepositPlatformAccount().setCurrencyCode(jyCurrencyCode).setMid(fundMoveDetail.get("payerAccountNo").toString()).queryFirst();
                                    if (tcwDepositPlatformAccount != null){
                                        tcwWanliPrepaymentPooling.setPayerAccountNo(tcwDepositPlatformAccount.getVyhzhmc());
                                        tcwWanliPrepaymentPooling.setVgsbm(tcwDepositPlatformAccount.getVgsbm());
                                    }
                                }
                                //收款人账号
                                if (fundMoveDetail.get("beneficiaryAccountNo") != null){
                                    tcwWanliPrepaymentPooling.setBeneficiaryAccountNo("86-18559907949");
                                    tcwWanliPrepaymentPooling.setBeneficiaryName(fundMoveDetail.get("beneficiaryName").toString());
                                    tcwWanliPrepaymentPooling.setSkMid(tcwDepositPlatform.getMid());
                                    tcwWanliPrepaymentPooling.setSkVyhsx(0);
                                }
                            }
                            //是否入账对账
                            tcwWanliPrepaymentPooling.setReconciliationStatus(0);
                            tcwWanliPrepaymentPooling.setRecordedStatus(0);

                            tcwWanliPrepaymentPoolingList.add(tcwWanliPrepaymentPooling);
                        }
                    }
                }
                pageNumber++;

                //判断是否还需要再获取数据
                if (Integer.valueOf(resultJO.get("totalPageNumber").toString()) < pageNumber){
                    falx = false;
                    continue;
                }

            }
            //批量新增
            int tcwWanliPrepaymentPoolingListLength = tcwWanliPrepaymentPoolingList.size();
            int j = 0;
            while (tcwWanliPrepaymentPoolingListLength > 50) {
                diySqlMapper.insetBatchTcwWanliPrepaymentPooling(tcwWanliPrepaymentPoolingList.subList(j, j + 50));
                j = j + 50;
                tcwWanliPrepaymentPoolingListLength = tcwWanliPrepaymentPoolingListLength - 50;
            }
            if (tcwWanliPrepaymentPoolingListLength > 0) {
                diySqlMapper.insetBatchTcwWanliPrepaymentPooling(tcwWanliPrepaymentPoolingList.subList(j, j + tcwWanliPrepaymentPoolingListLength));
            }
        }catch (Exception e){
            apiResponse.setCode(500);
            apiResponse.setMessage(e.getMessage());
            return apiResponse;
        }
        return apiResponse;

    }


    /**
     * 同步运营公司
     * @param idList
     * @return
     * @throws Exception
     */
    @Override
    public R tbVgsbm(List<String> idList) throws Exception {
        TcwWanliPrepaymentPooling tcwWanliPrepaymentPooling;
        TcwDepositPlatformAccount tcwDepositPlatformAccount;
        for (String id :  idList){
            //查询明细流水
            tcwWanliPrepaymentPooling = new TcwWanliPrepaymentPooling().setId(Long.valueOf(id)).queryFirst();
            if (tcwWanliPrepaymentPooling != null){
                //根据付款人账号获取Mid
                tcwDepositPlatformAccount = new TcwDepositPlatformAccount().setCurrencyCode(tcwWanliPrepaymentPooling.getJyCurrencyCode()).setVyhzhmc(tcwWanliPrepaymentPooling.getPayerAccountNo()).queryFirst();
                if (tcwDepositPlatformAccount != null){
                    tcwWanliPrepaymentPooling.setFkMid(tcwDepositPlatformAccount.getMid());
                    tcwWanliPrepaymentPooling.setVgsbm(tcwDepositPlatformAccount.getVgsbm());
                    tcwWanliPrepaymentPoolingMapper.update(tcwWanliPrepaymentPooling);
                }
            }
        }
        return R.ok();
    }

    /**
     * 修改Mid信息
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public R toEdit(Map<String, Object> params) {
        if (params.get("id") == null) {
            return R.error("该数据不存在!");
        }
        TcwWanliPrepaymentPooling tcwWanliPrepaymentPooling = new TcwWanliPrepaymentPooling().setId(Long.valueOf(params.get("id").toString())).queryFirst();
        if (tcwWanliPrepaymentPooling.getReconciliationStatus() == 1 || tcwWanliPrepaymentPooling.getRecordedStatus() == 1) {
            return R.error("该数据已对账或已入账,不允许修改!");
        }
        tcwWanliPrepaymentPooling.setFkMid(params.get("fkMid").toString());
        tcwWanliPrepaymentPooling.setPayerAccountNo(params.get("payerAccountNo").toString());
        tcwWanliPrepaymentPoolingMapper.update(tcwWanliPrepaymentPooling);
        return R.ok(EditDto.closeAndReload());
    }

    /**
     * 通过万里汇流水明细(付款状态更新1688订单对应的手续费
     * @return
     */
    @Override
    public ApiResponse inquiryStatementListPayment(TcwDepositPlatform tcwDepositPlatform) {
        ApiResponse apiResponse = new ApiResponse();
        JSONArray statementList;
        JSONObject statement;
        JSONObject platformFeeAmount;
        BigDecimal platformFeeAmountValue;
        JSONObject feeAmount;
        BigDecimal feeAmountValue;
        String jyCurrencyCode = null;
        String fwCurrencyCode = null;
        try {
            apiResponse.setCode(0);
            apiResponse.setMessage("获取成功!");
            String content = "";
            int pageNumber = 1;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("pageSize",50);

            //查询万里汇莫程账号clientId
            TbStaticConfig tbStaticConfigClientId = new TbStaticConfig()
                    .setKeyOne("wanli-mid")
                    .setKeyTwo("wanli-mid-clientId")
                    .queryFirst();


            //			当前天
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -7);

            calendar.set(Calendar.HOUR_OF_DAY,00);
            calendar.set(Calendar.MINUTE,00);
            calendar.set(Calendar.SECOND,00);

            Date startTime = calendar.getTime();
            String startTimeStr = DateUtils.convertDateToTDate(startTime);

            calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 0);

            calendar.set(Calendar.HOUR_OF_DAY,23);
            calendar.set(Calendar.MINUTE,59);
            calendar.set(Calendar.SECOND,59);

            Date endTime = calendar.getTime();
            String endTimeStr = DateUtils.convertDateToTDate(endTime);
            jsonObject.put("startTime",startTimeStr);
            jsonObject.put("endTime",endTimeStr);

            List<String> transactionTypeList = new ArrayList<>();
            transactionTypeList.add(TransactionTypeListEnum.Type.PAYMENT.value);//支付
            jsonObject.put("transactionTypeList",transactionTypeList);
            String httpMethod = WfSubUserEnum.Type.POST.value;
            //主账号有子账号
            String clientId = tbStaticConfigClientId.getName();
            String uriWithQueryString = WfSubUserEnum.Type.INQUIRYBENEFICIARYLIST.value;
            String connectedCustomerId = "";

            boolean falx = true;
            while (falx){
                jsonObject.put("pageNumber",pageNumber);
                content = JSONObject.toJSONString(jsonObject);
                String result = WanliUtils.result(content, httpMethod, uriWithQueryString, clientId,connectedCustomerId);
                JSONObject resultJO = JSON.parseObject(result);
                JSONObject resultState = JSON.parseObject(resultJO.get("result").toString());
                //判断是否成功
                if (!resultState.get("resultStatus").toString().equals(WfSubUserEnum.Type.S.value)){
                    apiResponse.setCode(500);
                    apiResponse.setMessage(resultState.get("resultMessage").toString());
                    return apiResponse;
                }

                if (resultJO.get("statementList") != null){
                    statementList = JSON.parseArray(resultJO.get("statementList").toString());
                    for (int i = 0; i < statementList.size(); i++) {
                        statement = JSON.parseObject(statementList.get(i).toString());
                        String extTransactionId = statement.get("extTransactionId").toString();
                        TcgPurchaseOrderPay tcgPurchaseOrderPay = new TcgPurchaseOrderPay()
                                .addLeftJoin("TCG_PurchaseByOrder B ON B.Bid= A.PurchaseOrderBid ")
                                .setPayType(1)//1.跨境宝
                                .where("B.OrderStatus = 7 AND A.chargeTrouble IS NULL AND A.chargeTroubleWf IS NULL AND B.aliOrderNumber = '" + extTransactionId + "'")
                                .queryFirst();
                        if (tcgPurchaseOrderPay != null){
                            //获取第三方平台收费金额
                            platformFeeAmount = JSON.parseObject(statement.get("platformFeeAmount").toString());
                            if (platformFeeAmount != null){
                                //JPY 不需要缩小100倍，其他都需要
                                jyCurrencyCode = platformFeeAmount.get("currency").toString();
                                if (jyCurrencyCode.equals(TcwExchangeRateEnum.ExchangeRate.JPY.value)){
                                    platformFeeAmountValue = new BigDecimal(platformFeeAmount.get("value").toString());
                                }else {
                                    platformFeeAmountValue = new BigDecimal(platformFeeAmount.get("value").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入);
                                }
                                tcgPurchaseOrderPay.setChargeTrouble(platformFeeAmountValue);
                            }
                            //获取万里汇服务费金额
                            feeAmount = JSON.parseObject(statement.get("feeAmount").toString());
                            if (feeAmount != null){
                                //JPY 不需要缩小100倍，其他都需要
                                fwCurrencyCode = feeAmount.get("currency").toString();
                                if (fwCurrencyCode.equals(TcwExchangeRateEnum.ExchangeRate.JPY.value)){
                                    feeAmountValue = new BigDecimal(feeAmount.get("value").toString());
                                }else {
                                    feeAmountValue = new BigDecimal(feeAmount.get("value").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入);
                                }
                                tcgPurchaseOrderPay.setChargeTroubleWf(feeAmountValue);
                            }
                            tcgPurchaseOrderPayMapper.update(tcgPurchaseOrderPay);

                        }
                    }
                }
                pageNumber++;

                //判断是否还需要再获取数据
                if (Integer.valueOf(resultJO.get("totalPageNumber").toString()) < pageNumber){
                    falx = false;
                    continue;
                }

            }
        }catch (Exception e){
            apiResponse.setCode(500);
            apiResponse.setMessage(e.getMessage());
            return apiResponse;
        }
        return apiResponse;

    }

    /**
     * 通过万里汇流水明细采购退款对应的手续费
     * @return
     */
    @Override
    public ApiResponse inquiryStatementListPaymentTh(TcwDepositPlatform tcwDepositPlatform, TccOnlinePurchaseReturn entity,String aliOrderNumber) {
        ApiResponse apiResponse = new ApiResponse();
        JSONArray statementList;
        JSONObject statement;
        JSONObject platformFeeAmount;
        BigDecimal platformFeeAmountValue = BigDecimal.ZERO;
        JSONObject feeAmount;
        BigDecimal feeAmountValue = BigDecimal.ZERO;
        String jyCurrencyCode = null;
        String fwCurrencyCode = null;
        try {
            apiResponse.setCode(0);
            apiResponse.setMessage("获取成功!");
            String content = "";
            int pageNumber = 1;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("pageSize",50);

            //查询万里汇莫程账号clientId
            TbStaticConfig tbStaticConfigClientId = new TbStaticConfig()
                    .setKeyOne("wanli-mid")
                    .setKeyTwo("wanli-mid-clientId")
                    .queryFirst();


            //			当前天
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -7);

            calendar.set(Calendar.HOUR_OF_DAY,00);
            calendar.set(Calendar.MINUTE,00);
            calendar.set(Calendar.SECOND,00);

            Date startTime = calendar.getTime();
            String startTimeStr = DateUtils.convertDateToTDate(startTime);

            calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 0);

            calendar.set(Calendar.HOUR_OF_DAY,23);
            calendar.set(Calendar.MINUTE,59);
            calendar.set(Calendar.SECOND,59);

            Date endTime = calendar.getTime();
            String endTimeStr = DateUtils.convertDateToTDate(endTime);
            jsonObject.put("startTime",startTimeStr);
            jsonObject.put("endTime",endTimeStr);

            List<String> transactionTypeList = new ArrayList<>();
            transactionTypeList.add(TransactionTypeListEnum.Type.REFUND.value);//退款
            jsonObject.put("transactionTypeList",transactionTypeList);
            String httpMethod = WfSubUserEnum.Type.POST.value;
            //主账号有子账号
            String clientId = tbStaticConfigClientId.getName();
            String uriWithQueryString = WfSubUserEnum.Type.INQUIRYBENEFICIARYLIST.value;
            String connectedCustomerId = "";

            boolean falx = true;
            while (falx){
                jsonObject.put("pageNumber",pageNumber);
                content = JSONObject.toJSONString(jsonObject);
                String result = WanliUtils.result(content, httpMethod, uriWithQueryString, clientId,connectedCustomerId);
                JSONObject resultJO = JSON.parseObject(result);
                JSONObject resultState = JSON.parseObject(resultJO.get("result").toString());
                //判断是否成功
                if (!resultState.get("resultStatus").toString().equals(WfSubUserEnum.Type.S.value)){
                    apiResponse.setCode(500);
                    apiResponse.setMessage(resultState.get("resultMessage").toString());
                    return apiResponse;
                }

                if (resultJO.get("statementList") != null){
                    statementList = JSON.parseArray(resultJO.get("statementList").toString());
                    for (int i = 0; i < statementList.size(); i++) {
                        statement = JSON.parseObject(statementList.get(i).toString());
                        String extTransactionId = statement.get("extTransactionId").toString();
                        if (extTransactionId.equals(aliOrderNumber)) {
                            //获取第三方平台收费金额
                            platformFeeAmount = JSON.parseObject(statement.get("platformFeeAmount").toString());
                            if (platformFeeAmount != null) {
                                //JPY 不需要缩小100倍，其他都需要
                                jyCurrencyCode = platformFeeAmount.get("currency").toString();
                                if (jyCurrencyCode.equals(TcwExchangeRateEnum.ExchangeRate.JPY.value)) {
                                    platformFeeAmountValue = new BigDecimal(platformFeeAmount.get("value").toString());
                                } else {
                                    platformFeeAmountValue = new BigDecimal(platformFeeAmount.get("value").toString()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入);
                                }
                            }
                            //获取万里汇服务费金额
                            feeAmount = JSON.parseObject(statement.get("feeAmount").toString());
                            if (feeAmount != null) {
                                //JPY 不需要缩小100倍，其他都需要
                                fwCurrencyCode = feeAmount.get("currency").toString();
                                if (fwCurrencyCode.equals(TcwExchangeRateEnum.ExchangeRate.JPY.value)) {
                                    feeAmountValue = new BigDecimal(feeAmount.get("value").toString());
                                } else {
                                    feeAmountValue = new BigDecimal(feeAmount.get("value").toString()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入);
                                }
                            }
                            entity.setRefund1688Charge(platformFeeAmountValue);
                            entity.setRefundWanliCharge(feeAmountValue);
                            entity.setRefundCommissionCharge(platformFeeAmountValue.add(feeAmountValue));
                        }
                    }
                }
                pageNumber++;

                //判断是否还需要再获取数据
                if (Integer.valueOf(resultJO.get("totalPageNumber").toString()) < pageNumber){
                    falx = false;
                    continue;
                }

            }
        }catch (Exception e){
            apiResponse.setCode(500);
            apiResponse.setMessage(e.getMessage());
            return apiResponse;
        }
        return apiResponse;

    }
}
